<template>
	<u-popup :show="open" @close="popupClose" @open="popupOpen" mode="bottom" :closeable="true"
		:closeOnClickOverlay="false" :customStyle="customStyle1" :round="20">
		<view class="wrapper" style="">
			<view class="blank20"></view>
			<view class="" v-if="addList.length>0">
				<text>已添加：</text>
				<template v-for="(v,i) in addList">
					<text>{{v.material_name}}{{v.qty}}{{v.unit_name}}{{i+1 == addList.length?'':'、'}}</text>
				</template>
			</view>
			<view class="blank20"></view>
			<view class="text-gray tips-box" v-if="type == 'cus'">请说出你要添加的客户名，如：“大幅”</view>
			<view class="text-gray tips-box" v-if="type == 'date'">请说出你要添加的日期，如：“2024年1月1日”</view>
			<view class="text-gray tips-box" v-if="type == 'info'">请说出你要添加的用餐信息，如：“中餐快餐50份”</view>
			<view class="blank20"></view>
			<view class="flex" v-if="type == 'date'">
				<u--input placeholder="日期" border="surround" type="text" v-model="date" @blur="check" :customStyle="dateError?inputErrorCustomStyle:inputCustomStyle"></u--input>
			</view>
			<view class="flex" v-if="type == 'cus'">
				<u--input placeholder="客户" border="surround" type="text" v-model="cus" @blur="check" :customStyle="cusError?inputErrorCustomStyle:inputCustomStyle"></u--input>
			</view>
			<view class="flex" v-if="type == 'info'">
				<view class="">
					<u--input placeholder="餐别" border="surround" type="text" v-model="dinnerType" @blur="check" :customStyle="dinnerTypeError?inputErrorCustomStyle:inputCustomStyle"></u--input>
				</view>
				<view class="ml10">
					<u--input placeholder="类别" border="surround" type="text" v-model="salesType" @blur="check"  :customStyle="salesTypeError?inputErrorCustomStyle:inputCustomStyle"></u--input>
				</view>
				<view class="ml10">
					<u--input placeholder="份数" border="surround" type="number" v-model="qty" @blur="check" :customStyle="qtyError?inputErrorCustomStyle:inputCustomStyle"></u--input>
				</view>
			</view>
			<template v-if="errorTips || tips">
				<view class="blank20"></view>
				<view v-if="errorTips" class="text-red">{{errorTips}}</view>
				<view v-if="tips">{{tips}}</view>
			</template>
			<view class="blank20"></view>
			<view class="flex">
				<!-- <view class="flex-1">
					<u-button text="确定" shape="circle" :plain="true" type="primary" size="small" :disabled="!isAdd"  @click="add"></u-button>
				</view>
				<view class="ml10 mr10"></view> -->
				<view class="flex-1">
					<u-button text="录入" shape="circle" :plain="true" type="primary" size="small" :disabled="!isAdd"  @click="add"></u-button>
				</view>
				<view class="ml10 mr10"></view>
				<view class="flex-1">
					<u-button text="录入后关闭" shape="circle" :plain="true" type="primary" size="small" @click="addAndClose" :disabled="!isAdd"></u-button>
				</view>
			</view>
			<!-- <view class="" v-if="longPress == '1'">
				上传文件毫秒数：{{uploadTime}}
			</view> -->
			<view class="blank20"></view>
			<template v-if="longPress == '2'">
				<view>
					<text class="text-red">松手停止</text>
					<text>，{{'剩余：' + count + 's'}}</text>
				</view>
				<view class="blank20"></view>
			</template>
			<view class="btn-recorder" @longpress="longpressBtn" @touchend="touchendBtn">
				{{longPress == '1' ? '按住说话' : '说话中...'}}
			</view>
			<!-- <view class="btn-recorder" @click="upload">
				电脑上测试上传音频
			</view> -->
			<!-- <u-button :text="btnText" shape="circle" :loading="btnLoading" type="success" @longpress="longpress"></u-button> -->
			<view class="blank20"></view>
		</view>

	</u-popup>
</template>

<script>
	import {
		upload
	} from '@/common/api.js';
	
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	let init; // 录制时长计时器
	let timer; // 播放 录制倒计时
	let uploadTimer; // 上传文件计时器

	export default {
		name: "recorder-popup",
		props: {
			open: Boolean,
			type:String
		},
		data() {
			return {
				uploadTime:0,//上传时长
				btnText: '按住 说话',
				btnLoading: false,
				customStyle1: {
					// 'background':'none'
				},
				count: null, // 录制倒计时
				longPress: '1', // 1显示 按住说话 2显示 说话中
				delShow: false, // 删除提示框显示隐藏
				time: 0, //录音时长
				duration: 60000, //录音最大值ms 60000/1分钟
				tempFilePath: '', //音频路径
				playStatus: 0, //录音播放状态 0:未播放 1:正在播放
				dinnerType:'',
				salesType:'',
				qty:'',
				date:'',
				cus:'',
				tips:'',
				errorTips:'',
				resultData:null,
				dinnerTypeError:false,
				qtyError:false,
				salesTypeError:false,
				dateError:false,
				cusError:false,
				inputErrorCustomStyle:{
					'border-color': '#ff0000 !important'
				},
				inputCustomStyle:{},
				addList:[],
				_upError:''
			};
		},
		watch:{
			open(newVal, oldVal) {
				this.resultData = null;
				this.dinnerType = '';
				this.salesType = '';
				this.qty = '';
				this.date = '';
				this.cus = '';
				this.tips = '';
				this.errorTips = '';
				this.addList = [];
				this.dinnerTypeError = false;
				this.salesTypeError = false;
				this.qtyError = false;
				this.dateError = false;
				this.cusError = false;
			}
		},
		computed:{
			isAdd(){
				let flag = false;
				if(this.dinnerType && this.salesType && this.qty){
					if(this.errorTips){
						flag = false;
					}else{
						flag = true;
					}
				}
				return flag;
			}
		},
		methods: {
			add(){
				let _this = this;
				this.$emit("add",{
					type:_this.type,
					dinnerType:_this.dinnerType,
					salesType:_this.salesType,
					qty:_this.qty,
				});
				// let item = JSON.parse(JSON.stringify(this.resultData));
				// this.addList.push(item)
			},
			addAndClose(){
				this.add();
				this.popupClose();
			},
			upload(){
				let _this = this;
				// let tempFilePath = '/static/test_voice_sc_mp3_16_mono.mp3';
				let tempFilePath = this.tempFilePath;
				uni.showLoading({
					title: '加载中'
				});
				let sales_category_list = this.$store.getters.get_sales_category_list;
				let category = sales_category_list.map(v=>{
					return v.name
				});
				let dinner_type_category = this.$store.getters.get_dinner_type_category;
				let dinner = dinner_type_category.map(v=>{
					return v.name
				});
				_this.recordingUploadTimer();
				// console.log(tempFilePath);
				console.log(JSON.stringify(category));
				console.log(JSON.stringify(dinner));
				uni.uploadFile({
					url: 'https://ai.fmn315.cn/upload_sale/',
					filePath: tempFilePath,
					name: 'file',
					formData: {
						'category':JSON.stringify(category),
						'dinner':JSON.stringify(dinner)
					},
					success: (uploadFileRes) => {
						// console.log(uploadFileRes);
						// console.log(result['食材名称']);
						try{
							let result = JSON.parse(JSON.parse(uploadFileRes.data));
							_this.dinnerType = result['餐别'];
							_this.salesType = result['类别'];
							_this.qty = result['数量'];
							
							uni.hideLoading();
						}catch(e){
							//TODO handle the exception
							uni.$u.toast('翻译失败');
						}
						this.check();
					},
					fail:(res)=>{
						// console.log('[https://ai.fmn315.cn/upload_sale]uploadFile-fail');
						// console.log(res);
						// _upError
						// this._upError = JSON.stringify(res);
						uni.$u.toast('上传失败');
					},
					complete:()=>{
						_this.recordingUploadTimer(1);
					}
				});
			},
			check(){
				let _this = this;
				this.errorTips = "搜索中，请稍等...";
				this.tips = '';
				this.dinnerTypeError = false;
				this.salesTypeError = false;
				this.qtyError = false;
				this.cusError = false;
				this.dateError = false;
				
				if(!_this.dinnerType){
					this.dinnerTypeError = true;
					this.errorTips = "餐别有误；";
					return;
				}
				if(!_this.salesType){
					this.salesTypeError = true;
					this.errorTips = "类别有误；";
					return;
				}
				if(!_this.qty){
					this.qtyError = true;
					this.errorTips = "份数有误；";
					return;
				}
				
				let searchResult = {
					dinnerTypeError:false,
					salesTypeError:false,
					tips:''
				};
				this.$emit("check",{
					type:_this.type,
					dinnerType:_this.dinnerType,
					salesType:_this.salesType,
					qty:_this.qty,
				},searchResult);
				
				this.dinnerTypeError = searchResult.dinnerTypeError;
				this.salesTypeError = searchResult.salesTypeError;
				this.errorTips = "";
				
				if(_this.type == 'info'){
					if(!this.dinnerTypeError && !this.salesTypeError){
						this.errorTips = "";
						this.tips = '点击【录入】或【录入后关闭】，即可添加：'+searchResult.tips;
					}
					if(this.dinnerTypeError){
						this.errorTips += "餐别有误；";
						this.tips = '';
					}
					if(this.salesTypeError){
						this.errorTips += "类别有误；";
						this.tips = '';
					}
				}
			},
			popupClose() {
				// this.open = false;
				this.$emit("close");
			},
			popupOpen() {

			},
			longpressBtn() {
				console.log('longpress');
			},
			touchendBtn() {

			},
			// 倒计时
			countdown(val) {
				let _then = this;
				if(!val){
					clearInterval(timer);
				}
				_then.count = Number(val);
				timer = setInterval(function() {
					if (_then.count > 0) {
						_then.count--
					} else {
						_then.longPress = '1';
						clearInterval(timer);
					}
				}, 1000);
			},
			// 长按录音事件
			longpressBtn() {
				this.longPress = '2';
				this.countdown(60); // 倒计时
				clearInterval(init) // 清除定时器
				// return;
				recorderManager.onStop((res) => {
					console.log('录音停止recorderManager.onStop1');
					this.tempFilePath = res.tempFilePath;
					this.recordingTimer(this.time);
					this.countdown(); // 清除倒计时
				})
				const options = {
					duration: this.duration, // 指定录音的时长，单位 ms
					sampleRate: 16000, // 采样率
					numberOfChannels: 1, // 录音通道数
					encodeBitRate: 96000, // 编码码率
					format: 'mp3', // 音频格式，有效值 aac/mp3
					frameSize: 10, // 指定帧大小，单位 KB
				}
				this.recordingTimer();
				recorderManager.start(options);
				// 监听音频开始事件
				recorderManager.onStart((res) => {
					// console.log('recorderManager.onStart');
					// console.log(res)
				})
			},
			// 长按松开录音事件
			touchendBtn() {
				this.longPress = '1';
				// return;
				recorderManager.onStop((res) => {
					console.log('录音停止recorderManager.onStop2');
					// console.log(res);
					this.tempFilePath = res.tempFilePath;
					this.upload();
				})
				this.recordingTimer(this.time);
				this.countdown(); // 清除倒计时
				recorderManager.stop()
			},
			recordingTimer(time) {
				let that = this;
				if (time == undefined) {
					// 将计时器赋值给init
					init = setInterval(function() {
						that.time++
					}, 1000);
				} else {
					clearInterval(init)
				}
			},
			recordingUploadTimer(time) {
				let that = this;
				if (time == undefined) {
					// 将计时器赋值给uploadTimer
					that.uploadTime = 0;
					uploadTimer = setInterval(function() {
						that.uploadTime++
					}, 1);
				} else {
					console.log('上传文件毫秒数：'+that.uploadTime);
					clearInterval(uploadTimer)
				}
			},
			// 删除录音
			delBtn() {
				this.delShow = false;
				this.time = 0
				this.tempFilePath = ''
				this.playStatus = 0
				innerAudioContext.stop()
			},
			// 播放
			playBtn() {
				innerAudioContext.src = this.tempFilePath
				//在ios下静音时播放没有声音，默认为true，改为false就好了。
				// innerAudioContext.obeyMuteSwitch = false
				//点击播放
				if (this.playStatus == 0) {
					this.playStatus = 1;
					innerAudioContext.play();
					this.countdown(this.time); // 倒计时
				} else {
					this.playStatus = 0;
					innerAudioContext.pause()
				}
				// //播放结束
				innerAudioContext.onEnded(() => {
					this.playStatus = 0;
					innerAudioContext.stop();
				})
			},
		}
	}
</script>

<style>
	.btn-recorder {
		border-radius: 70upx;
		line-height: 70upx;
		color: #fff;
		background-color: #5ac725;
		border-color: #5ac725;
		border-width: 1px;
		border-style: solid;
		text-align: center;
	}
</style>